<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Pagination, Zoom } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/zoom'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* ---- */
const user = reactive({
  isLink: false,
  telphone: proxy.$telPhone,
  wechat_img: proxy.$imgEwm,
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon,
  // ----
  name: '',
  desc: '',
  isFold: false,
  // ----
  display: 1,
  displayText: '',
  // ----
  musicPlay: 'paused',
  musicId: 0,
  musicUrl: ''
})
// ----
const totalCount = ref(0)
let advsData = []
// ----
const displays = [{
  value: '1',
  text: '左右滑动'
}, {
  value: '2',
  text: '上下滑动'
}]
// ----
const forPagination = ref({})
const modules = [Pagination, Zoom]
// ----
let musics = []
const tbtns = ref([])
// ----
const fold = reactive({
  count: 3,
  height: 0,
  info: ''
})
// ----
const items = ref([])

/* ---- */
const preImg = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const onSwiper = (swiper) => {
  user.name = swiper.slides[swiper.activeIndex].getAttribute('data-name')
  user.desc = swiper.slides[swiper.activeIndex].getAttribute('data-desc')
  if (String(swiper.slides[swiper.activeIndex].getAttribute('data-fold')) === 'true') {
    user.isFold = true
  } else {
    user.isFold = false
  }
}
const onSlideChange = (swiper) => {
  user.name = swiper.slides[swiper.activeIndex].getAttribute('data-name')
  user.desc = swiper.slides[swiper.activeIndex].getAttribute('data-desc')
  if (String(swiper.slides[swiper.activeIndex].getAttribute('data-fold')) === 'true') {
    user.isFold = true
  } else {
    user.isFold = false
  }
}
// ----
const audioPlay = () => {
  proxy.$refs.bgMusic.play()
  document.removeEventListener('touchstart', audioPlay)
}
// ----
const getCurrencyInfo = async () => {
  fold.height = proxy.$refs.forTrueHeight.offsetHeight
  // --获取背景音乐集--
  const musicItems = forSys.filter((item) => { return String(item.name) === 'market_bgMusic' })
  if (Number(musicItems.length) === 1) {
    await proxy.$Myfun.getJsonData(musicItems[0].value, (resJson) => {
      if (Number(resJson[0].list.length) > 0) musics = resJson[0].list
    })
  }
  // --获取用户信息 & 相册信息 & 图片信息--
  const forUserData = { params: { 'DealerSearch[id]': proxy.$route.query.dealer_id } }
  const forPhotoData = { params: { 'AlbumCategorySearch[id]': proxy.$route.query.id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forUserData),
    proxy.$Axios.get('album-category/index', forPhotoData)
  ]).then(proxy.$Axios.spread(async (userData, photoData) => {
    // --用户信息--
    const UData = userData.items[0] || {}
    user.telphone = UData.tag || UData.telphone
    proxy.$Myfun.getJsonData(UData.wechat_img, (resJson) => {
      if (Number(resJson.length) > 0) user.wechat_img = resJson[0].image
    })
    proxy.$Myfun.getJsonData(UData.avatar, (resJson) => {
      if (Number(resJson.length) > 0) user.share_icon = resJson[0].image
    })
    // --相册信息--
    const PData = photoData.items[0] || {}
    user.isLink = Number(PData.is_invite) === 1
    user.title = proxy.$Myfun.setText(PData.name)
    user.share_title = proxy.$Myfun.setText(PData.name)
    // ----
    proxy.$Myfun.getJsonData(PData.remark, (resJson) => {
      const RJData = resJson[0] || {}
      if (RJData.description) user.share_desc = RJData.description
      if (RJData.display_id) user.display = RJData.display_id
      if (RJData.music_id) user.musicId = RJData.music_id
      if (RJData.share_img && Number(RJData.share_img.length) > 0) user.share_icon = RJData.share_img[0].image
      // ----
      if (RJData.customer) {
        if (RJData.customer.telphone && Number(RJData.customer.telphone.length) > 0) user.telphone = RJData.customer.telphone
        if (RJData.customer.wechat_img && Number(RJData.customer.wechat_img.length) > 0) user.wechat_img = RJData.customer.wechat_img[0].image
      }
      // ----
      if (RJData.albums && Number(RJData.albums.length) > 0) advsData = RJData.albums
    })
    // ----
    displays.some((current) => {
      if (String(current.value) === String(user.display)) user.displayText = current.text
    })
    // --设置分页样式--
    if (Number(user.display) === 1) {
      forPagination.value = {
        type: 'custom',
        renderCustom: (swiper, current, total) => {
          return '<span></span><div>' + user.displayText + '</div>' + current + ' / ' + total + '<span></span>'
        }
      }
    }
    // --图片信息--
    totalCount.value = advsData.length
    await setListData(advsData).then((result) => { items.value = result })
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  musics.some((current) => {
    if (String(current.id) === String(user.musicId)) user.musicUrl = current.link
  })
  // --获取分享者联系方式--
  if (proxy.$route.query.sn) {
    await proxy.$http.get('dealer/index', {
      params: { 'DealerSearch[sn]': proxy.$route.query.sn }
    }).then((res) => {
      const UData = res.items[0] || {}
      user.telphone = UData.tag || UData.telphone
      proxy.$Myfun.getJsonData(UData.wechat_img, (resJson) => {
        if (Number(resJson.length) > 0) user.wechat_img = resJson[0].image
      })
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  tbtns.value = [{
    show: user.musicUrl && Number(user.musicUrl.length) > 0,
    icon: 'fal fa-music-note xw-color-18',
    style: 'TBX-rgba xw-radius-round INIT-rotate',
    music: true,
    callback: () => {
      if (String(user.musicPlay) === 'running') {
        proxy.$refs.bgMusic.pause()
      } else {
        proxy.$refs.bgMusic.play()
      }
    }
  }, {
    show: true,
    icon: 'fal fa-comments xw-color-18',
    style: 'TBX-rgba xw-radius-round',
    callback: () => {
      let options = {
        title: proxy.$Global.layer.titleTwo + user.telphone,
        content: proxy.$Global.layer.conEver,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnAsk,
          class: 'xw-color-24',
          callback: () => { window.location.href = 'tel:' + user.telphone }
        }]
      }
      if (user.wechat_img) {
        options = {
          title: proxy.$Global.layer.titleThree,
          content: '<div style="padding: 0 2.4rem;"><img src="' + user.wechat_img + '" style="width: 100%;"/></div>',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: proxy.$Global.layer.btnAsk,
            class: 'xw-color-24',
            callback: () => { window.location.href = 'tel:' + user.telphone }
          }]
        }
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
    }
  }, {
    show: true,
    icon: 'fal fa-phone-volume xw-color-18',
    style: 'TBX-rgba xw-radius-round',
    callback: () => { window.location.href = 'tel:' + user.telphone }
  }, {
    show: user.isLink,
    icon: 'fal fa-cart-plus xw-color-18',
    style: 'TBX-rgba xw-radius-round',
    callback: () => { proxy.$Myfun.openPage(proxy, 'push', 'GoodsHome', { dealer_id: proxy.$route.query.dealer_id }) }
  }]
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // --设置微信分享信息--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  if (user.musicUrl && Number(user.musicUrl.length) > 0) document.addEventListener('touchstart', audioPlay)
}
// ----
const getFoldState = () => {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      const curFoldH = proxy.$refs.forTrueHeight.offsetHeight
      if (Number(curFoldH / fold.height) > Number(fold.count)) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const advItems = [{
      msrc: item.image,
      src: item.image,
      width: item.width,
      height: item.height,
      alt: ''
    }]
    // ----
    let forFold = false
    fold.info = proxy.$Myfun.setText(item.content)
    if (Number(user.display) === 1) await getFoldState().then((result) => { forFold = result })
    // ----
    newItems.push({
      name: proxy.$Myfun.setText(item.title),
      desc: fold.info,
      image: item.image,
      advs: advItems,
      // ----
      isFold: forFold
    })
    // ----
    fold.info = ''
  }
  return newItems
}
// ----
const getAuditFun = (type, item, event) => {
  switch (Number(type)) {
    case 1: {
      if (Number(item.advs.length) > 0) {
        const curEL = event.currentTarget
        const options = {
          actElement: curEL,
          addopt: {
            loop: true,
            dataSource: item.advs
          }
        }
        proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      }
      break
    }
    case 2: {
      item.callback && item.callback()
      break
    }
    case 3: {
      user.musicPlay = 'paused'
      break
    }
    case 4: {
      user.musicPlay = 'running'
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo()
})
onBeforeUnmount(() => { document.removeEventListener('touchstart', audioPlay) })
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <template v-if="Number(user.display) === 1">
      <div class="xw-full">
        <transition name="fade">
          <swiper :modules="modules" :pagination="forPagination" :loop="true" :zoom="true" @swiper="onSwiper" @slideChange="onSlideChange" class="album-box" v-if="Number(items.length) > 0">
            <swiper-slide v-for="(item, index) in items" :data-name="item.name" :data-desc="item.desc" :data-fold="item.isFold">
              <div class="swiper-zoom-container"><img :src="item.image"/></div>
            </swiper-slide>
          </swiper>
        </transition>
      </div>
      <transition name="fade">
        <div class="FBR-con" v-if="user.name || user.desc">
          <div class="FBR-name xw-ellipsis" v-if="user.name">{{user.name}}</div>
          <div class="FBR-desc xw-flex" v-if="user.desc">
            <input type="checkbox" id="check_album" class="xw-fold-handle"/>
            <div class="xw-fold-text">
              <label class="xw-fold-btn" for="check_album" v-if="user.isFold"></label>
              {{user.desc}}
            </div>
          </div>
        </div>
      </transition>
      <div class="list-li list-li-fold"><div ref="forTrueHeight">{{fold.info}}</div></div>
    </template>
    <template v-if="Number(user.display) === 2">
      <transition name="fade">
        <div class="invit-list" v-if="Number(items.length) > 0">
          <div v-for="(item, index) in items">
            <div class="ILT-top xw-flex xw-flex-align">
              <span class="xw-flex-W1"></span><div>{{user.displayText}}</div>{{index + 1}} / {{totalCount}}<span class="xw-flex-W1"></span>
            </div>
            <div class="ILT-img" @click="getAuditFun(1, item, $event)"><img :src="item.image"/></div>
            <div class="ILT-con xw-bg-white" v-if="item.name || item.desc">
              <div class="ILT-title" v-if="item.name">{{item.name}}</div>
              <div class="ILT-desc" v-if="item.desc">{{item.desc}}</div>
            </div>
          </div>
        </div>
      </transition>
    </template>
    <div class="tabfix">
      <template v-for="(item, index) in tbtns">
        <template v-if="item.show">
        <a class="xw-flex xw-flex-center xw-flex-column" :class="item.style" :style="{'animation-play-state': user.musicPlay}" @click="getAuditFun(2, item)" v-if="item.music">
          <em :class="item.icon" v-if="item.icon"></em><span v-html="item.name" v-if="item.name"></span>
        </a>
        <a class="xw-flex xw-flex-center xw-flex-column" :class="item.style" @click="getAuditFun(2, item)" v-else>
          <em :class="item.icon" v-if="item.icon"></em><span v-html="item.name" v-if="item.name"></span>
        </a>
        </template>
      </template>
    </div>
    <div class="INIT-audio"><audio ref="bgMusic" :src="user.musicUrl" @pause="getAuditFun(3)" @play="getAuditFun(4)" preload loop></audio></div>
    <preImg-view ref="preImg"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.xw-full { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0, 0, 0, 0.8); }

/* ---- */
.ILT-top { padding: 1rem 0; }
.ILT-top span { flex: 1; margin: 0 1rem; height: 0.1rem; background: rgba(0, 0, 0, 0.2); }
.ILT-top div { margin-right: 2rem; }
.ILT-img img { width: 100%; }
.ILT-con { padding: 1.6rem 1rem 0.6rem; }
.ILT-title { margin: 0 0 1rem; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.ILT-desc { margin: 0 0 1rem; line-height: 2rem; }

/* ---- */
.FBR-close { position: absolute; padding: 1rem; right: 0; top: 0; color: #ffffff; z-index: 999; }

/* ---- */
.FBR-con { position: fixed; padding: 6rem 0 1rem 0; right: 0; bottom: 0; left: 0; color: #ffffff; text-shadow: 0 0 0.4rem rgba(0, 0, 0, 1); background-image: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5)); pointer-events: none; z-index: 99; }
.FBR-name { padding: 0 6rem 0 1rem; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; pointer-events: auto; }
.FBR-desc { margin: 0.5rem 0 0; padding: 0 6rem 0 1rem; font-size: 1.3rem; overflow: visible; pointer-events: auto; }
.list-li-fold { padding: 0 6rem 0 1rem; }
.list-li-fold div { min-height: 2rem; line-height: 2rem; font-size: 1.3rem; text-align: justify; }

/* ---- */
.INIT-rotate { animation: rotating 3s linear infinite; }
.INIT-audio { display: none; height: 0; }

/* ---- */
@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
<style>
/* ---- */
.album-box { width: 100%; height: 100%; }
.album-box .swiper-pagination-custom { padding: 1rem 0 6rem; bottom: auto; top: 0; left: 0; color: #ffffff; background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); display: flex; align-items: center; }
.album-box .swiper-pagination-custom span { flex: 1; margin: 0 1rem; height: 0.1rem; background: rgba(255, 255, 255, 0.2); }
.album-box .swiper-pagination-custom div { margin-right: 2rem; }
</style>